#version 130

// Las matrices de transformacion
uniform mat4 viewMatrix;
uniform mat4 modelMatrix;
uniform mat4 projectionMatrix;

// Los datos para la iluminacion
uniform mat3 normalMatrix;
uniform vec3 direccionLuz;

// Para el fragment shader
out vec3 ReflectDir; // The direction of the reflected ray

vec3 ExtractCameraPos_NoScale(mat4 modelView){
  mat3 rotMat=mat3(modelView);
  vec3 d=vec3(modelView[3]);
  vec3 retVec = -d * rotMat;
  return retVec;
}

vec3 ExtractCameraPos(mat4 modelView)
{
  // Get the 3 basis vector planes at the camera origin and transform them into model space.
  //  
  // NOTE: Planes have to be transformed by the inverse transpose of a matrix
  //
  // As each plane is simply (1,0,0,0), (0,1,0,0), (0,0,1,0) we can pull the data directly from the transpose matrix.
  //  
  mat4 modelViewT = transpose(modelView);
 
  // Get plane normals 
  vec3 n1=vec3(modelViewT[0]);
  vec3 n2=vec3(modelViewT[1]);
  vec3 n3=vec3(modelViewT[2]);
 
  // Get plane distances
  float d1=modelViewT[0].w;
  float d2=modelViewT[1].w;
  float d3=modelViewT[2].w;
 
  // Get the intersection of these 3 planes
  vec3 n2n3 = cross(n2, n3);
  vec3 n3n1 = cross(n3, n1);
  vec3 n1n2 = cross(n1, n2);
 
  vec3 top = (n2n3 * d1) + (n3n1 * d2) + (n1n2 * d3);
  float denom = dot(n1, n2n3);
 
  return top / -denom;
}

void main(){
	// Se necesitan las normales interpoladas, por eso las paso al fragment shader
	//normal = normalize( normalMatrix * gl_Normal );

	mat4 modelViewMatrix=  viewMatrix * modelMatrix;

	vec3 WCPosition= ExtractCameraPos(modelViewMatrix);

	// Compute the reflected direction in world coords
	vec3 worldPos = vec3( modelMatrix *	gl_Vertex);

	//vec3 worldNorm = vec3(modelMatrix *	vec4(gl_Normal,0.0));
	vec3 worldNorm = gl_Normal;
	
	vec3 worldView = normalize(WCPosition - worldPos);

	ReflectDir = reflect(-worldView, worldNorm );

	// Calcula la posicion del vertice
	gl_Position = projectionMatrix * viewMatrix * modelMatrix * gl_Vertex;
}
